<template>
  <div>
    <div class="before"></div>
    <van-form validate-first @failed="onFailed">
     
      <!-- 通过 validator 进行函数校验 -->
      <van-field
        v-model="value2"
        name="validator"
        label="用户名"
        placeholder=""
        :rules="[{ validator, message: '用户名不可用' }]"
      />
       <!-- 通过 pattern 进行正则校验 -->
      <van-field
        v-model="value1"
        name="pattern"
        label="密码"
        type="password"
        placeholder="请输入8位以上密码，密码中必须同时包含数字、字母"
        :rules="[{ pattern, message: '密码太过简单' }]"
      />
      <!-- 通过 validator 进行异步函数校验 -->
      <van-field
        v-model="value3"
        name="validator"
        label="手机号码"
        placeholder="请输入手机号码"
        :rules="[{ validator, message: '手机号不可用' }]"
      />
      <div style="margin: 16px" @click="regin"
      :class="!isRegin?'event':''"
      >
        <van-button
          round
          block
          native-type="submit"
          style="background: black; color: #fff"
        >
          注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Form } from "vant";
import { Toast } from "vant";

export default {
  data() {
    return {
      value1: "",
      value2: "",
      value3: "",
      pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,30}$/,
      isRegin:false,
    };
  },
  computed: {
    newUser() {
      return {
        username: this.value2,
        password: this.value1,
        phone: this.value3,
        isOnline:false,
      };
    },
     users() {
        return this.$store.state.user.user
      },
  },
  methods: {
    regin() {
      this.$store.commit("user/addUser", this.newUser);
      this.$router.push({
        path:'/'
      })
    },

    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator(val) {
      let bool=true;
      if(val==this.value2){
         for(let i=0;i<this.users.length;i++){
        if(val==this.users[i].username){
          bool=false
          break;
        }
      }
      }else if(val==this.value3){
        if(/^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/.test(val)){
            for(let i=0;i<this.users.length;i++){
            if(val==this.users[i].phone){
          bool=false
          break;
        }
         }
        }else{
          bool=false
        }
       
      }
     this.isRegin=bool
      return bool;
    },
    onFailed(errorInfo) {
      console.log("failed", errorInfo);
    },
  },
};
</script>

<style lang="scss" scoped>
.before {
  height: 100px;
  width: 100%;
}
.title {
  color: black;
  text-align: center;
}
.title a {
  color: blue;
}
.event{
  pointer-events: none;
}
</style>